package org.lonetree.tc.webapp.actions;

import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.Book;
import org.lonetree.tc.core.Book.Isbn;
import org.lonetree.tc.core.dao.BookDAO;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.webapp.forms.BookForm;

public class CreateBook extends Action {

	

	@Override
	public ActionForward execute(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		try {
			BookForm abf=(BookForm) form;
			Isbn isbn=new Isbn(abf.getIsbn());
			DAOFactory fac = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY);
			BookDAO bdao = fac.getBookDAO();
			Book book=bdao.createBook(isbn);
			book.setOptional(false);
			book.setTitle(abf.getTitle());
			//empty set
			Set<String> bookauthors=book.getAuthors();
			String[] authors=abf.getAuthor().split(",");
			for (String s:authors)
				bookauthors.add(s);//add authors	
			bdao.updateBook(book);
			return mapping.findForward("success");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return mapping.findForward("failure");
		}
	}

}
